package com.gs.SynPatrolRep.db.dao;

import android.database.sqlite.SQLiteDatabase;

import com.gs.SynPatrolRep.MyApplication;
import com.gs.SynPatrolRep.db.domain.DaoMaster;
import com.gs.SynPatrolRep.db.domain.DaoSession;

public class DBUtil {
    private static volatile DBUtil instance;
    private static final String DB_NAME = "cache.db";
    private DaoMaster.DevOpenHelper mOpenHelper;
    private DaoSession mReadDaoSession,mWriteDaoSession;

    public static DBUtil getInstance(){
        if (instance == null) {
            synchronized (DBUtil.class){
                if (instance == null) {
                    instance = new DBUtil();
                }
            }
        }
        return instance;
    }

    public DBUtil() {
    }

    private void initDbHelper(){
        if (mOpenHelper == null) {
            mOpenHelper = new DaoMaster.DevOpenHelper(MyApplication.getContext(),DB_NAME,null);
        }
    }

    public DaoSession getWriteDaoSession(){
        if (mWriteDaoSession == null) {
            mWriteDaoSession = new DaoMaster(getWritableDatabase()).newSession();
        }
        return mWriteDaoSession;
    }

    private SQLiteDatabase getWritableDatabase(){
        initDbHelper();
        return mOpenHelper.getWritableDatabase();
    }

    public DaoSession getReadDaoSession(){
        if (mReadDaoSession == null) {
            mReadDaoSession = new DaoMaster(getReadableDatabase()).newSession();
        }
        return mReadDaoSession;
    }

    private SQLiteDatabase getReadableDatabase() {
        initDbHelper();
        return mOpenHelper.getReadableDatabase();
    }

    public void closeConnection(){
        closeHelper();
        closeDaoSession();
    }

    private void closeHelper() {
        if (mOpenHelper != null) {
            mOpenHelper.close();
            mOpenHelper = null;
        }
    }

    private void closeDaoSession() {
        if (mReadDaoSession != null) {
            mReadDaoSession.clear();
            mReadDaoSession = null;
        }

        if (mWriteDaoSession != null) {
            mWriteDaoSession.clear();
            mWriteDaoSession = null;
        }
    }
}
